#include "mainwindow.h"

#include <QFile>
#include <QMenu>
#include <QTime>
#include <QTimer>
#include <QVBoxLayout>

#include "ui_mainwindow.h"
#include "videofactory.h"
#include "word/wordtab.h"

const QString FFMPEG = "./misc/ffmpeg";

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent), ui(new Ui::MainWindow) {
    ui->setupUi(this);
    setWindowTitle("Chores");
    // setWindowIcon(QIcon(":/Res/Chores.png"));
    this->loadStyleSheet(":/mainwindow.qss");

    setupClock();
    setupFileTransfer();
    setupVideoFactory();
    // setupTray();
    WordTab* word = new WordTab(this);
    ui->tabWidget->addTab(word, "字词");
    ui->tabWidget->setCurrentWidget(word);
}

MainWindow::~MainWindow() { delete ui; }

void MainWindow::addPage(Page p) {
    if (p.widget) {
        // ui->lwsidebar->addItem(p.name);
        // ui->stackedWidget->addWidget(p.widget);
    }
}

void MainWindow::loadStyleSheet(const QString qssfile) {
    QFile qss(qssfile);

    qss.open(QFile::ReadOnly);
    if (qss.isOpen()) {
        QString styleSheet = this->styleSheet();
        styleSheet += QLatin1String(qss.readAll());  // 读取样式表文件
        this->setStyleSheet(styleSheet);             // 把文件内容传参
    }
    qss.close();
}

void MainWindow::creatSubtitleDialog() {}

void MainWindow::closeEvent(QCloseEvent* e) {
    if (m_tray && m_tray->isVisible()) {  // 托盘还在
        e->ignore();                      // ① 不继续关闭
        hide();                           // ② 仅隐藏窗口
        m_tray->showMessage("提示", "程序已最小化到托盘",
                            QSystemTrayIcon::Information, 2000);
    } else {
        e->accept();  // 真的退出
    }
    QWidget::closeEvent(e);
}

void MainWindow::setupVideoFactory() {
    VideoFactory* vf = new VideoFactory(ui->tab_video);
    vf->resize(ui->tab_video->size());
}

void MainWindow::setupTray() {
    m_tray = new QSystemTrayIcon(this);
    m_tray->setIcon(QIcon(":/Res/Chores.png"));
    m_tray->setToolTip("单击打开");

    QMenu* menu = new QMenu(this);
    QAction* openAction = new QAction("打开主面板", this);
    connect(openAction, &QAction::triggered, this, &MainWindow::showNormal);
    menu->addAction(openAction);

    QAction* quitAction = new QAction("退出", this);
    connect(quitAction, &QAction::triggered, qApp, &QCoreApplication::quit);
    //    connect(quitAction, &QAction::triggered, this, &MainWindow::close);
    menu->addAction(quitAction);

    // Set the context menu for the tray icon
    m_tray->setContextMenu(menu);

    connect(m_tray, &QSystemTrayIcon::activated,
            [this](QSystemTrayIcon::ActivationReason reason) {
                switch (reason) {
                    case QSystemTrayIcon::Trigger:
                        if (!isVisible()) {
                            showNormal();
                        } else {
                            hide();
                        }
                        break;
                    default:
                        break;
                }
            });
    m_tray->show();
}

void MainWindow::setupClock() {
    //    m_effect = new QSoundEffect(this);
    m_timer = new QTimer(this);
    m_bell_timer = new QTimer(this);
    m_bell_timer->callOnTimeout(this, &MainWindow::bell);
    ui->progressBar->setFormat("当前进度: 0%");
    ui->progressBar->setAlignment(Qt::AlignRight | Qt::AlignCenter);
    QStringList headers;
    headers << "开始时间"
            << "结束时间"
            << "间隔"
            << "描述";
    ui->twclock->setColumnCount(headers.size());
    ui->twclock->setHorizontalHeaderLabels(headers);

    connect(m_timer, &QTimer::timeout, this, &MainWindow::onTimeOut);
}

void MainWindow::setupFileTransfer() {
    QStringList headers;
    headers << "IP地址"
            << "端口"
            << "文件名称"
            << "文件大小"
            << "当前包"
            << "发送进度";
    // ui->twserver->setHorizontalHeaderLabels(headers);
    // ui->twclient->setHorizontalHeaderLabels(headers);
}

void MainWindow::on_pb_start_clicked() {
    static bool click_start = true;
    ui->progressBar->setValue(0);
    int hours = ui->spb_hours->value();
    int min = ui->spb_min->value();
    int total_minute = min + hours * 60;
    ui->progressBar->setMaximum(total_minute * 60);

    ui->spb_hours->setEnabled(!click_start);
    ui->spb_min->setEnabled(!click_start);
    if (click_start) {
        // 注册定时器事件bell
        m_bell_timer->start(total_minute * 60 * 1000);
        // 进度条更新
        m_timer->start(1000);
        ui->pb_start->setText("点击结束计时");
        click_start = false;

        // TB-添加开始时间
        QTime time = QTime::currentTime();
        QTableWidgetItem* item = new QTableWidgetItem(time.toString("H:m:s"));
        int row = ui->twclock->rowCount();
        ui->twclock->insertRow(row);
        ui->twclock->setItem(row, twclock_start, item);
        // TB-添加描述
        item = new QTableWidgetItem(ui->le_des->text());
        ui->twclock->setItem(row, twclock_des, item);

    } else {
        m_timer->stop();
        m_bell_timer->stop();
        //        m_effect->stop();
        ui->pb_start->setText("计时开始");
        ui->progressBar->setFormat("当前进度: 0%");
        click_start = true;

        // TB-添加结束时间
        QTime time = QTime::currentTime();
        QTableWidgetItem* item = new QTableWidgetItem(time.toString("H:m:s"));
        int row = ui->twclock->rowCount() - 1;
        ui->twclock->setItem(row, twclock_stop, item);

        // TB-计算间隔时间
        QString start_time = ui->twclock->item(row, twclock_start)->text();
        QTime start = QTime::fromString(start_time, "H:m:s");
        int hour = time.hour() - start.hour();
        int minu = time.minute() - start.minute();
        int sec = time.second() - start.second();
        QString interval = QString::asprintf("%d:%d:%d", hour, minu, sec);

        item = new QTableWidgetItem(interval);
        ui->twclock->setItem(row, twclock_interval, item);
    }
}

void MainWindow::bell() {
    //    m_effect->setSource(QUrl::fromLocalFile("fl.wav"));
    //    m_effect->setSource(QUrl(":res/fl.wav"));
    //    m_effect->setLoopCount(QSoundEffect::Infinite);
    //    m_effect->setVolume(1.0f);
    //    m_effect->play();
    //    ui->pb_start->setText("停止");
}

void MainWindow::onTimeOut() {
    quint64 current = ui->progressBar->value();
    current += 1;
    ui->progressBar->setValue(current);
    double progress = current * 100 / ui->progressBar->maximum();
    if (progress > 100) {
        m_timer->stop();
    }
    ui->progressBar->setFormat(
        "当前进度: " + QString::number(progress, 'f', 2) + "%");
}

// void MainWindow::mouseReleaseEvent(QMouseEvent* event) {
//     if (event->button() == Qt::LeftButton) {
//         //        m_dragPosition = QPoint();
//         event->accept();
//     }
// }
//
// void MainWindow::mousePressEvent(QMouseEvent* event) {
//     if (event->button() == Qt::LeftButton) {
//         m_startPoint = frameGeometry().topLeft() - event->globalPos();
//     }
// }
//
// void MainWindow::mouseMoveEvent(QMouseEvent* event) {
//     this->move(event->globalPos() + m_startPoint);
// }
//
